// pages/add_dev/add_dev.js
var app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rangekey:0,
    deviceClassId:'',
    devNick:'',
    devID:'',
    describe:'',
    // init_input_devnick:'',
    // init_input_devID:'',
    list:[],
    list_arr:[],
    deviceClassId:''    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if(app.globalData.is_login === false){
      wx.showModal({
        title: '提示',
        content: '请先登录,才可以添加设备',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../login/login',
            });
            return;
          } else if (res.cancel) {

          }
        }
      });
    }

   
    // that.setData({
    //   list:app.globalData.global_group
    // });

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
   
    wx.request({
      url: 'https://119.3.46.145/server/FindGroup?userid=' + app.globalData.userid ,
      method: 'POST',
      header: header,
      success: res => {   //error== "0"表示设备添加成功 -1表示设备已存在
        // console.log(res,"res");
        that.setData({
          list:JSON.parse(res.data.data),
          deviceClassId: JSON.parse(res.data.data)[0].groupId
        });        
      },
      fail: function (error) {
        console.log(error, "add_dev find_group error");
      }
    })  

    // let tmp_array = [];
    // that.data.list.forEach(function(item, index, self){
    //   tmp_array.push(item.groupName);
    // });

    // that.setData({
    //   list_arr: tmp_array
    // });
  },

  getDevnick:function(e){
    let that = this;
    that.setData({
      devNick:e.detail.value
    });
  },

  getDevID:function(e){
    let that = this;
    that.setData({
      devID:e.detail.value
    });   
  },


  clear: function () {
    let that = this;

    that.setData({
      devNick: "",
      devID: ""
    });
  },

  bindTextAreaBlur: function (e) {
    let that = this;
    that.setData({
      describe: e.detail.value
    });
  },

  add_devID:function(){
    let that = this;
    if(that.data.devID===""){     
      wx.showModal({
        title: '必填项不能为空',
        content: '设备号不能为空！',
      });
      return;
    }

    //console.log(that.data.describe, "that.data.describe ");

    if (that.data.describe ==""){      
      wx.showModal({
        title: '必填项不能为空',
        content: '描述不能为空！',
      });
      return;
    }

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    

    /**+ '&devnick=' + that.data.devNick */
    wx.request({
      url: 'https://119.3.46.145/server/AddDevice?userid=' + app.globalData.userid + 'deviceid=' + that.data.devID + '&description=' + that.data.describe +"&devClassId="+that.data.deviceClassId,
      method: 'POST',
      header: header,
      success: res => {        
        //error== "0"表示设备添加成功 -1表示设备已存在
        if(res.data.error == 0){
          //跟新一下 全局变量  app.globalData.dev_list 获取最新的设备列表 在请求getLastInfo的时候用
          //方式一  直接请求最新的
          wx.request({
            url: "https://119.3.46.145/server/FindDevice?userid=" + app.globalData.userid,
            type: "post",
            header: header,
            success: res => {
              //如果没有设备 则return
              if (res.data == '') {
                app.globalData.dev_list = [];
                return;
              }

              let devices_data = JSON.parse(res.data.devices);
              app.globalData.dev_list = devices_data;   
              //console.log(app.globalData.dev_list, "app.globalData.dev_list")   ;        
            },
            fail:function(error){
              console.log("add_dev FindDevice error"+error);
            }
          });

          //方式二 直接修改数组
          // app.globalData.dev_list.push({
          //   devNo: that.data.devID,
          //   groupId: that.data.devClassId,
          //   description: that.data.describe
          // });


          wx.showModal({
            title: '数据添加成功',
            content: '点击确定返回上一页',
            success(res) {
              if (res.confirm) {
                let pages = getCurrentPages(); //获取上一个页面信息栈(a页面)
                let prevPage = pages[pages.length - 2] 
                prevPage.add_change(that.data.devClassId, that.data.devID, that.data.describe);
                wx.navigateBack(); //关闭当前页面，返回上一个页面           
              } else if (res.cancel) {
                
              }
            }
          })
        }

        if(res.data.error == "-1"){
          wx.showModal({
            title: '提示',
            content: '设备已存在'
          })
        }
      },
      fail: function (error) {
        console.log(error, "AddDevice error");
      },
      complete: function (complete) {

      }
    })  
  },

//组选择器触发函数  bindblur有bug必须在form 的submit函数获得
  bindPickerChange:function(e){   
    let that = this;
    if(that.data.list.length == 0){
      wx.showModal({
        title: '提示',
        content: '当前无分组，请先创建分组',
        success(res) {
          if (res.confirm) {
            //console.log('用户点击确定')
            wx.navigateTo({
              url: '../add_group/add_group',
            });           

          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      })
    }

    that.setData({
      rangekey: e.detail.value
    });

    that.data.list.forEach(function(item, index, self){
      if(index == that.data.rangekey){
        that.setData({
          deviceClassId:item.groupId
        });
      }
    });
  },

  formSubmit:function(e){
    let that = this;
    
    that.setData({
      describe:e.detail.value.textarea,
      devID:e.detail.value.input
    });
    if (that.data.devID === "") {
      wx.showModal({
        title: '必填项不能为空',
        content: '设备号不能为空！',
      });
      return;
    }

    //console.log(that.data.describe, "that.data.describe ");

    if (that.data.describe == "" || that.data.describe == undefined || that.data.describe == null) {
      wx.showModal({
        title: '必填项不能为空',
        content: '描述不能为空！',
      });
      return;
    }

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    /**+ '&devnick=' + that.data.devNick */
    wx.request({
      url: 'https://119.3.46.145/server/AddDevice?userid=' + app.globalData.userid + '&deviceid=' + that.data.devID + '&description=' + that.data.describe + "&devClassId=" + that.data.deviceClassId,
      method: 'POST',
      header: header,
      success: res => {
        //error== "0"表示设备添加成功 -1表示设备已存在
        if (res.data.error == "0") {
          wx.request({
            url: "https://119.3.46.145/server/FindDevice?userid=" + app.globalData.userid,
            type: "post",
            header: header,
            success: res => {
              app.globalData.edit_del_add_dev_flag = true; //增加过这个，标记改为 true 需要重新设置地图的 center 以及scale
              //如果没有设备 则return
              if (res.data == '') {
                app.globalData.dev_list = [];
                return;
              }

              let devices_data = JSON.parse(res.data.devices);
              app.globalData.dev_list = devices_data;
             
            },
            fail: function (error) {
              console.log("add_dev FindDevice error" + error);
            }
          });
          wx.showModal({
            title: '数据添加成功',
            content: '点击确定返回上一页',
            success(res) {
              if (res.confirm) {
                let pages = getCurrentPages(); //获取上一个页面信息栈(a页面)
                let prevPage = pages[pages.length - 2]
                prevPage.add_change(that.data.deviceClassId, that.data.devID, that.data.describe);
                wx.navigateBack(); //关闭当前页面，返回上一个页面           
              } else if (res.cancel) {

              }
            }
          })
        }
        if(res.data.error == "-1"){
          wx.showModal({
            title: '提示',
            content: '设备已存在'
          })
        };
      },
      fail: function (error) {
        console.log(error, "AddDevice error");
      }
    })      
  },

  formReset:function(e){

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})